﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.SessionState;

namespace RC1
{
    public partial class downloadFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user_id"] != null)
            {
                int id = Convert.ToInt32(Request.QueryString["id"]);
                download(id);
            }
            else
            {
                Response.Redirect("login.aspx");
            }
        }

        private void download(int id)
        {
            if (Convert.ToInt32(Session["user_level"]) > 0)
            {
                tsu2011db4Entities1 db = new tsu2011db4Entities1();

                var file = (from f in db.files
                            where f.file_id == id
                            select f).SingleOrDefault();
                if (file != null)
                {
                    byte[] fileContent = file.file_content;
                    String strExtenstion = file.file_type;

                    Response.Clear();
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("content-disposition", "attachment; filename=" + file.file_name);
                    Response.BinaryWrite(fileContent);
                    Response.ContentType = "";
                    Response.End();
                }
            }
            else
            {
                int user_id = Convert.ToInt32(Session["user_id"]);
                tsu2011db4Entities1 db = new tsu2011db4Entities1();

                var file = (from f in db.files
                            join s in db.submissions on f.file_id equals s.file_id
                            where f.file_id == id
                            where s.user_id == user_id
                            select f).SingleOrDefault();
                if (file != null)
                {
                    byte[] fileContent = file.file_content;
                    String strExtenstion = file.file_type;

                    Response.Clear();
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("content-disposition", "attachment; filename=" + file.file_name);
                    Response.BinaryWrite(fileContent);
                    Response.ContentType = "";
                    Response.End();
                }
            }
        }
    }
}